package com.itbaiyun.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itbaiyun.usercenter.common.ErrorCode;
import com.itbaiyun.usercenter.common.PageRequest;
import com.itbaiyun.usercenter.common.ResultUtil;
import com.itbaiyun.usercenter.exception.BusinessException;
import com.itbaiyun.usercenter.model.domain.User;
import com.itbaiyun.usercenter.model.dto.UserSearchDto;
import com.itbaiyun.usercenter.service.UserService;
import com.itbaiyun.usercenter.mapper.UserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.text.Collator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.itbaiyun.usercenter.common.ErrorCode.PARAMS_NULL_ERROR;
import static com.itbaiyun.usercenter.common.ErrorCode.SYSTEM_ERROR;
import static com.itbaiyun.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.itbaiyun.usercenter.constant.UserConstant.USER_LOGIN_STATE;


/**
 * @author O
 * @description 针对表【user(用户表)】的数据库操作Service实现  用户服务实现类
 * @createDate 2024-05-09 20:22:24
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;
    /**
     * 盐值,混淆密码
     */
    private static final String SALT = "yeye";


    @Override
    public long UserRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        //1.校验(导入Commons依赖简化)
//        if (userAccount==null||userPassword==null||checkPassword==null){
//
//        }
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        //2.校验账户
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度小于4");
        }

        //3.密码校验
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度有误");
        }

        //对plantCode做校验
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号长度不能大于5");
        }


        //4.账户不能包含特殊字符
        String regex = "^[a-zA-Z0-9._]+$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能包含特殊字符");
        }

        //5.校验密码和二次密码是否一致
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码输入不一致");
        }
        //6.账户不能重复(在数据库中查询是否有相同的名字)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该账号已存在");
        }

        //星球编号不能重复(plantCode)
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plantCode", planetCode);
        long counts = userMapper.selectCount(queryWrapper);
        if (counts > 0) {
            //存在,返回负一,,说明注册失败
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号已存在");
        }


        //7.密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);

        user.setPlanetCode(planetCode);
        boolean save = this.save(user);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "");
        }

        return user.getId();
    }


    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验用户
        //1.校验(导入Commons依赖简化)
//        if (userAccount==null||userPassword==null||checkPassword==null){
//
//        }
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(PARAMS_NULL_ERROR);
        }

        //2.校验账户
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号长度不能小于4!");
        }

        //3.密码校验
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8!");
        }

        //4.账户不能包含特殊字符
        String regex = "^[a-zA-Z0-9._]+$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户不能包含特殊字符!");
        }

        //.密码加密
//        final String SALT = "yeye";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);

        //用户不存在
        if (user == null) {
            log.info("user login fail,userAccount cannot match userPassword");
            throw new BusinessException(PARAMS_NULL_ERROR);
        }
        //3.用户脱敏
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setGender(user.getGender());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setTags(user.getTags());

        //4.记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }


    /**
     * 用户注销
     *
     * @param request 移除用户登录态
     */
    @Override
    public int UserLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }


    /**
     * 根据标签 搜索用户
     *
     * @param tagNameList 用户要拥有的标签
     * @return 返回搜索结果
     */
    @Override
    public List<User> searchUserByTags(List<String> tagNameList) {
//        //判断参数是否为空
//        if (CollectionUtils.isEmpty(tagNameList)){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        for (String tagName : tagNameList){
//            queryWrapper = queryWrapper.like("tags",tagName);
//        }
//       List<User> userList = userMapper.selectList(queryWrapper);

        //内存查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //查询所有用户
        List<User> userList = userMapper.selectList(queryWrapper);
        //再在内存中判断是否包含要求的标签
        Gson gson = new Gson();
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            //如果查询出来的为空则返回false
            if (StringUtils.isBlank(tagsStr)) {
                return false;
            }
            //序列化
            Set<String> templateTagNameList = gson.fromJson(tagsStr, new TypeToken<List<User>>() {
            }.getType());
            for (String tagName : tagNameList) {
                if (!templateTagNameList.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
//       return userList.stream(). map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    @Override
    public int updateUser(User user, User loginUser) {
        //权限判断(仅管理员和本用户可以修改)
        //获取登录用户id
        long userId = loginUser.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //不是管理员,只能更新当前用户
        if (!isAdmin(loginUser) && userId != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //管理员可修改所有人的信息
            //找到要修改信息的用户
            User oldUser = userMapper.selectById(userId);
            //判断要修改的用户是否存在
            if (oldUser == null) {
                throw new BusinessException(PARAMS_NULL_ERROR);
            }
            return userMapper.updateById(user);
    }


    /**
     * 获取当前用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Object objUser = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (objUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return (User) objUser;
    }


    @Override
    /**
     * 抽取出来的是否为管理员的方法
     *
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request) {
        //鉴权  仅管理员可查询
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }

    @Override
    /**
     * 抽取出来的是否为管理员的方法
     *
     * @param loginUser
     * @return
     */
    public boolean isAdmin(User loginUser) {
        //鉴权  仅管理员可查询
        return loginUser == null && loginUser.getUserRole() != ADMIN_ROLE ? false : true;
    }


    /**
     *  用户更换头像实现
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean changeAvatar(User user,String avatarUrl) {
        //判空
        if (StringUtils.isBlank(avatarUrl)){
            throw new BusinessException(PARAMS_NULL_ERROR,"头像不能为空!");
        }
        user.setAvatarUrl(avatarUrl);
        boolean result = this.updateById(user);
        if (!result){
            throw new BusinessException(SYSTEM_ERROR,"更新失败~");
        }
        return result;
    }


}




